use std::time::Instant;

use common::debug;
use image::{GenericImage, GenericImageView, ImageResult, Rgba};
use std::ops::{Div, Mul};

use crate::ArrayRes;

#[tauri::command]
pub fn img_merge(front: String, back: String) -> ArrayRes {
    let t = Instant::now();

    let root_path = common::file::root_path();
    if root_path.is_none() {
        eprintln!("root path get failed");
        return (-1, "root path get failed".to_string());
    }
    let root_path = root_path.unwrap();
    let output_path = root_path + "/tmp" + "/file_result.png";

    let res = image_deal_img(&front, &back, &output_path);
    if res.is_err() {
        return (
            -1,
            format!("out_path={}, err={:?}", output_path, res.unwrap_err()),
        );
    }

    debug!("cost={:?}", Instant::now().duration_since(t));

    (0, output_path)
}

/// 此处两个open和最后一个save所占时间较长
fn image_deal_img(name1: &str, name2: &str, output_name: &str) -> ImageResult<()> {
    let front = image::open(name1)?;
    let mut back = image::open(name2)?;

    let (x, y) = front.dimensions();
    let mut part = front.crop_imm(0, 0, x, y);

    //获取背景尺寸
    let (w, h) = back.dimensions();
    let new_w = (h as f64).div(y as f64).mul(x as f64) as u32;
    //将区域尺寸重置为背景尺寸
    part = part.resize(new_w, h, image::imageops::FilterType::Gaussian);
    let (qw, qh) = part.dimensions();

    //设置透明渐变
    for i in 0..w {
        if i >= qw {
            continue;
        }
        for j in 0..h {
            if j >= qh {
                continue;
            }
            let color = part.get_pixel(i, j);
            let tmp = 255u32.checked_sub(i / 3);
            let alpha = if tmp.is_none() { 0 } else { tmp.unwrap() };
            let color0 = color.0;
            let color = Rgba::from([color0[0], color0[1], color0[2], alpha as u8]);
            part.put_pixel(i, j, color);
        }
    }

    image::imageops::overlay(&mut back, &part, 0, 0);

    back.save(output_name)?;
    Ok(())
}
